<?php
class Records 
{
    const _CONST_TB_DEFAULT_ = 'tg_logs';
    const _CONST_DB_DEFAULT_ = 'default';

    public static function add ($msgtype, $message, $uid = NULL)
    {
        if (empty($uid))
            $uid = user::current_user_id();

        $data = array(
            'types'   => self::typeid($msgtype),
            'uid'     => $uid,
            'message' => $message,
            'ctime'   => time(),
        );

        list($id, $rows) = DB::insert(self::_CONST_TB_DEFAULT_)
            ->columns (array_keys($data))
            ->values  (array_values($data))
            ->execute(self::_CONST_DB_DEFAULT_);

        return $id;
    }

    public static function counts ($msgtype = NULL)
    {
        $query = DB::select(array(DB::expr('count(*)'), 'count'))
            ->from(self::_CONST_TB_DEFAULT_);

        if (! empty($msgtype))
            $query->where('types', '=', self::typeid($msgtype));

        return $query->execute(self::_CONST_DB_DEFAULT_)->get('count');
    }

    public static function get ($offset = 0, $limit = 20, $msgtype = NULL)
    {
        $query = DB::select()
            ->from(self::_CONST_TB_DEFAULT_)
            ->offset($offset)
            ->limit($limit)
            ->order_by('ctime', 'DESC');

        if (! empty($msgtype))
            $query->where('types', '=', self::typeid($msgtype));

        $query  = $query->execute(self::_CONST_DB_DEFAULT_);
        $result = array();

        foreach ($query as $rs)
        {
            $uid = $rs['uid'];
            $uname = user::name($uid);
            $rs['name'] = $uname;
            $result[] = $rs;
        }

        return $result;
    }


    private static function typeid ($msgtype)
    {
        $key = "records.$msgtype";
        $kid = Kohana::config("records.$msgtype");
        if (empty($kid))
            throw new Exception("INVALID MSGTYPE: $key");

        return $kid;
    }
}
